﻿using System;
using System.Collections.Generic;
using System.Reflection;
using TimeTravel.Commons;
using TimeTravel.Components;
using TimeTravel.IData;

namespace TimeTravel.DataProvider
{
    /// <summary>
    /// 数据访问接口
    /// </summary>
    public static class DataAccess
    {
        private static readonly string Path;
        private static readonly Dictionary<Type, String> DataDict;
        static DataAccess()
        {
            Path = ConfigHelper.GetConfigString(ConstantInfo.AppSettingConstant.DataProviderKey);
            if (String.IsNullOrEmpty(Path))
            {
                throw new Exception("获取数据提供程序失败。请检查web.config文件中是否已配置数据提供程序！");
            }
            DataDict = new Dictionary<Type, string>
                           {
                               {typeof (IAnnouncementData), "AnnouncementData"},
                               {typeof (IClientInfoData), "ClientInfoData"},
                               {typeof (IFriendLinkData), "FriendLinkData"},
                               {typeof (IMailTemplateData), "MailTemplateData"},
                               {typeof (IManageLogData), "ManageLogData"},
                               {typeof (INavMenuData), "NavMenuData"},
                               {typeof (IRecentNewData), "RecentNewData"},
                               {typeof (IProductData), "ProductData"},
                               {typeof (ISiteMessageData), "SiteMessageData"},
                               {typeof (ISysLogData), "SysLogData"},
                               {typeof (ISysRoleData), "SysRoleData"},
                               {typeof (ISysUserData), "SysUserData"},
                               {typeof (IVisitorData), "VisitorData"}
                           };
        }

        /// <summary>
        /// 获取数据提供程序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        /// <exception cref="ArgumentException">获取数据提供程序失败</exception>
        public static T CreateDataInstance<T>()
        {
            string className;
            var result = DataDict.TryGetValue(typeof(T), out className);
            if (result)
            {
                return (T)Assembly.Load(Path).CreateInstance(Path + "." + className);
            }
            throw new ArgumentException("在指定的字典中未查询到："+typeof(T)+" 的数据提供程序！");
        }
    }
}
